import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import {
  Card,
  Upload,
  Button,
  Steps,
  Form,
  Input,
  Select,
  InputNumber,
  message,
  Progress,
  Space,
  Divider,
  Row,
  Col,
  Typography,
  Result,
} from "antd";
import {
  UploadOutlined,
  FileTextOutlined,
  EditOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
} from "@ant-design/icons";
import type { UploadProps } from "antd";
import styled from "styled-components";

// 类型定义
interface GeneratedContent {
  knowledgePoints: string[];
  exercises: Exercise[];
  timeDistribution: TimeDistribution;
}

interface Exercise {
  title: string;
  difficulty: "easy" | "medium" | "hard";
  type: "choice" | "programming" | "analysis";
}

interface TimeDistribution {
  theory: number;
  practice: number;
  qa: number;
}

interface FormValues extends Omit<GeneratedContent, "exercises"> {
  exercises: (Exercise & { key: string })[];
}

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const ContentPreview = styled.div`
  padding: 24px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-top: 16px;
`;

const TeacherPreparation: React.FC = () => {
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState(0);
  const [generatingContent, setGeneratingContent] = useState(false);
  const [generatedContent, setGeneratedContent] = useState<any>(null);
  const [form] = Form.useForm();
  const [autoSaveTimer, setAutoSaveTimer] = useState<NodeJS.Timeout | null>(
    null
  );
  const [lastSaved, setLastSaved] = useState<Date | null>(null);
  const [aiGenerating, setAiGenerating] = useState(false);
  const [aiSuggestions, setAiSuggestions] = useState<string[]>([]);

  const uploadProps: UploadProps = {
    name: "file",
    action: "/api/upload",
    headers: {
      authorization: "authorization-text",
    },
    onChange(info) {
      if (info.file.status === "done") {
        message.success(`${info.file.name} 文件上传成功`);
        // 上传成功后调用 AI 生成
        generateAIContent(info.file.response.content);
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };

  const handleGenerateContent = async () => {
    setGeneratingContent(true);
    // 模拟生成内容的过程
    setTimeout(() => {
      setGeneratedContent({
        knowledgePoints: [
          "变量与数据类型",
          "控制流程",
          "函数与方法",
          "面向对象编程基础",
        ],
        exercises: [
          {
            title: "编写一个计算斐波那契数列的函数",
            difficulty: "中等",
            type: "编程题",
          },
          {
            title: "解释面向对象编程中的封装概念",
            difficulty: "简单",
            type: "概念题",
          },
        ],
        timeDistribution: {
          theory: 30,
          practice: 45,
          qa: 15,
        },
      });
      setGeneratingContent(false);
      setCurrentStep(1);
    }, 2000);
  };

  const generateAIContent = async (syllabusContent: string) => {
    setAiGenerating(true);
    try {
      // 这里应该调用实际的 OpenAI API
      // 模拟 API 调用
      await new Promise((resolve) => setTimeout(resolve, 2000));

      const mockSuggestions = [
        "建议在第一章增加'嵌入式系统发展历史'的内容",
        "可以在实践环节加入'基于 ARM 的硬件平台实验'",
        "建议增加'实时操作系统原理'的知识点",
      ];

      setAiSuggestions(mockSuggestions);

      const mockContent = {
        knowledgePoints: [
          "嵌入式系统概述",
          "硬件平台设计",
          "软件开发流程",
          "RTOS原理与应用",
        ],
        exercises: [
          {
            title: "分析嵌入式系统的实时性需求",
            difficulty: "medium",
            type: "analysis",
          },
          {
            title: "设计简单的任务调度算法",
            difficulty: "hard",
            type: "programming",
          },
        ],
        timeDistribution: {
          theory: 45,
          practice: 60,
          qa: 15,
        },
      };

      setGeneratedContent(mockContent);
      message.success("AI 内容生成成功！");
    } catch (error) {
      console.error("AI generation failed:", error);
      message.error("AI 内容生成失败，请重试");
    } finally {
      setAiGenerating(false);
    }
  };

  const handleAutoSave = async (values: any) => {
    try {
      // 这里应该调用实际的保存API
      console.log("Auto saving...", values);
      setLastSaved(new Date());
      message.success("自动保存成功", 1);
    } catch (error) {
      console.error("Auto save failed:", error);
      message.error("自动保存失败，请手动保存");
    }
  };

  const handleFormChange = () => {
    if (autoSaveTimer) {
      clearTimeout(autoSaveTimer);
    }

    const timer = setTimeout(async () => {
      const values = await form.validateFields().catch(() => null);
      if (values) {
        handleAutoSave(values);
      }
    }, 30000); // 30秒后自动保存

    setAutoSaveTimer(timer);
  };

  useEffect(() => {
    return () => {
      if (autoSaveTimer) {
        clearTimeout(autoSaveTimer);
      }
    };
  }, [autoSaveTimer]);

  const handleSave = async (values: FormValues) => {
    try {
      console.log("保存的内容：", values);
      setLastSaved(new Date());
      message.success("保存成功！");
      setCurrentStep(2);
    } catch (error) {
      console.error("Save failed:", error);
      message.error("保存失败，请重试");
    }
  };

  const steps = [
    {
      title: "内容生成",
      description: "上传课程大纲并生成教学内容",
    },
    {
      title: "内容调整",
      description: "调整生成的教学内容",
    },
    {
      title: "完成",
      description: "预览并保存",
    },
  ];

  return (
    <div>
      <Steps current={currentStep} items={steps} style={{ marginBottom: 24 }} />

      {currentStep === 0 && (
        <StyledCard title="上传课程大纲">
          <Space direction="vertical" style={{ width: "100%" }}>
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
            <Paragraph type="secondary">
              支持上传 Word、PDF、TXT 格式的课程大纲文件
            </Paragraph>
            <Button
              type="primary"
              icon={<FileTextOutlined />}
              onClick={handleGenerateContent}
              loading={generatingContent || aiGenerating}
              style={{ marginTop: 16 }}
            >
              {aiGenerating ? "AI 正在分析内容..." : "开始生成教学内容"}
            </Button>
            {(generatingContent || aiGenerating) && (
              <Progress
                percent={45}
                status="active"
                style={{ marginTop: 16 }}
              />
            )}
            {aiSuggestions.length > 0 && (
              <Card title="AI 建议" size="small" style={{ marginTop: 16 }}>
                <ul>
                  {aiSuggestions.map((suggestion, index) => (
                    <li key={index}>{suggestion}</li>
                  ))}
                </ul>
              </Card>
            )}
          </Space>
        </StyledCard>
      )}

      {currentStep === 1 && generatedContent && (
        <Form
          form={form}
          onFinish={handleSave}
          layout="vertical"
          onValuesChange={handleFormChange}
        >
          <StyledCard title="知识点编辑">
            <Form.List
              name="knowledgePoints"
              initialValue={generatedContent.knowledgePoints}
            >
              {(fields, { add, remove }) => (
                <>
                  {fields.map((field, index) => (
                    <Form.Item required={false} key={field.key}>
                      <Form.Item
                        {...field}
                        validateTrigger={["onChange", "onBlur"]}
                        noStyle
                      >
                        <Input
                          placeholder="请输入知识点"
                          style={{ width: "60%" }}
                        />
                      </Form.Item>
                      <Space style={{ marginLeft: 8 }}>
                        {fields.length > 1 && (
                          <Button
                            type="link"
                            onClick={() => remove(field.name)}
                          >
                            删除
                          </Button>
                        )}
                      </Space>
                    </Form.Item>
                  ))}
                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => add()}
                      icon={<EditOutlined />}
                    >
                      添加知识点
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </StyledCard>

          <StyledCard title="实训练习设置">
            <Form.List
              name="exercises"
              initialValue={generatedContent.exercises}
            >
              {(fields, { add, remove }) => (
                <>
                  {fields.map((field, index) => (
                    <Card key={field.key} style={{ marginBottom: 16 }}>
                      <Row gutter={16}>
                        <Col span={12}>
                          <Form.Item
                            {...field}
                            label="题目"
                            name={[field.name, "title"]}
                          >
                            <TextArea rows={2} />
                          </Form.Item>
                        </Col>
                        <Col span={6}>
                          <Form.Item
                            {...field}
                            label="难度"
                            name={[field.name, "difficulty"]}
                          >
                            <Select>
                              <Option value="简单">简单</Option>
                              <Option value="中等">中等</Option>
                              <Option value="困难">困难</Option>
                            </Select>
                          </Form.Item>
                        </Col>
                        <Col span={6}>
                          <Form.Item
                            {...field}
                            label="类型"
                            name={[field.name, "type"]}
                          >
                            <Select>
                              <Option value="概念题">概念题</Option>
                              <Option value="编程题">编程题</Option>
                              <Option value="分析题">分析题</Option>
                            </Select>
                          </Form.Item>
                        </Col>
                      </Row>
                      <Button type="link" onClick={() => remove(field.name)}>
                        删除此题
                      </Button>
                    </Card>
                  ))}
                  <Button type="dashed" onClick={() => add()} block>
                    添加练习题
                  </Button>
                </>
              )}
            </Form.List>
          </StyledCard>

          <StyledCard title="时间分配">
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item
                  label="理论讲解"
                  name={["timeDistribution", "theory"]}
                  initialValue={generatedContent.timeDistribution.theory}
                >
                  <InputNumber<number>
                    min={0}
                    max={120}
                    formatter={(value) => `${value}分钟`}
                    parser={(value) => {
                      const parsed = value
                        ? parseInt(value.replace("分钟", ""))
                        : 0;
                      return Math.min(Math.max(parsed, 0), 120);
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="实践操作"
                  name={["timeDistribution", "practice"]}
                  initialValue={generatedContent.timeDistribution.practice}
                >
                  <InputNumber<number>
                    min={0}
                    max={120}
                    formatter={(value) => `${value}分钟`}
                    parser={(value) => {
                      const parsed = value
                        ? parseInt(value.replace("分钟", ""))
                        : 0;
                      return Math.min(Math.max(parsed, 0), 120);
                    }}
                  />
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  label="答疑互动"
                  name={["timeDistribution", "qa"]}
                  initialValue={generatedContent.timeDistribution.qa}
                >
                  <InputNumber<number>
                    min={0}
                    max={120}
                    formatter={(value) => `${value}分钟`}
                    parser={(value) => {
                      const parsed = value
                        ? parseInt(value.replace("分钟", ""))
                        : 0;
                      return Math.min(Math.max(parsed, 0), 120);
                    }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </StyledCard>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setCurrentStep(0)}>返回</Button>
              {lastSaved && (
                <Text type="secondary">
                  上次保存: {lastSaved.toLocaleTimeString()}
                </Text>
              )}
            </Space>
          </Form.Item>
        </Form>
      )}

      {currentStep === 2 && (
        <StyledCard title="预览">
          <Result
            status="success"
            title="备课内容已保存"
            subTitle="您可以在课件资源管理中查看和编辑此教案"
            extra={[
              <Button
                type="primary"
                key="console"
                onClick={() => setCurrentStep(0)}
              >
                继续备课
              </Button>,
              <Button key="buy" onClick={() => navigate("/teacher/resources")}>
                查看所有教案
              </Button>,
            ]}
          />
        </StyledCard>
      )}
    </div>
  );
};

export default TeacherPreparation;
